package com.ak.game.netty;

import com.ak.game.service.*;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;

public class WebSocketChannelInitializer extends ChannelInitializer<Channel> {

    private final PnGameService gameService;

    private final String websocketPath;

    private final RemoteWebSocketClientService clientService;

    private final BettingService bettingService;

    private final String gameId;

    private final PnVipUserService vipUserService;

    private final PnUserStreamService userStreamService;

    private final PnGameRecordService gameRecordService;

    public WebSocketChannelInitializer(String path, PnGameService gameService, RemoteWebSocketClientService clientService, BettingService bettingService, String gameId, PnVipUserService vipUserService, PnUserStreamService userStreamService, PnGameRecordService gameRecordService) {
        this.gameService = gameService;
        this.websocketPath = path;
        this.clientService = clientService;
        this.bettingService = bettingService;
        this.gameId = gameId;
        this.vipUserService = vipUserService;
        this.userStreamService = userStreamService;
        this.gameRecordService = gameRecordService;
    }

    /**
     * 重写ChannelInitializer的initChannel方法，用于配置Channel的处理器链
     *
     * @param channel 通道
     */
    @Override
    public void initChannel(Channel channel) {
        //获取Channel的管道，用于添加处理器
        ChannelPipeline pipeline = channel.pipeline();
        //添加HTTP编解码器，用于将字节流解码为HTTP请求或响应，反之亦然
        pipeline.addLast(new HttpServerCodec());
        //添加HTTP消息聚合处理器，将多个HTTP消息聚合为单一的FullHttpRequest或FullHttpResponse
        //这样可以一次处理完整个HTTP请求或响应，避免了大消息体的分片问题
        pipeline.addLast(new HttpObjectAggregator(65536));
        pipeline.addLast("corsHandler", new CorsHandler());
        //添加自定义的握手验证处理器
        pipeline.addLast(new WebSocketAuthHandler(gameService, websocketPath, clientService, gameId, vipUserService, userStreamService, gameRecordService));
        //添加WebSocket服务器协议处理器，用于处理WebSocket握手及协议升级，
        //websocketPath参数指定了WebSocket握手的URL路径，null表示使用默认的WebSocket版本，true表示对子协议的支持
//        pipeline.addLast(new WebSocketServerProtocolHandler(websocketPath, null, true));
        //添加自定义的WebSocket消息处理器，用于处理WebSocket连接建立后的文本或二进制消息
        pipeline.addLast(new WebSocketFrameHandler(gameId, clientService, bettingService, vipUserService, userStreamService, gameRecordService)); //自定义WebSocket消息处理器
    }

}
